package com.gln.bloger.exception;

import java.io.PrintStream;
import java.io.PrintWriter;

/**
 * Base exception for bloger
 * 
 * @author LeoLeung
 * Date: 2008/01/05
 */
public class BlogerException extends Exception {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Throwable rootCause = null;

	/**
	 * Construct emtpy exception object.
	 */
	public BlogerException() {
		super();
	}

	/**
	 * Construct BlogerException with message .
	 * 
	 * @param msg
	 *            error message string
	 */
	public BlogerException(String msg) {
		super(msg);
	}

	/**
	 * Construct BlogerException, wrapping existing throwable.
	 * 
	 * @param s
	 *            error message
	 * @param t
	 *            existing connection to wrap.
	 */
	public BlogerException(String msg, Throwable t) {
		super(msg);
		rootCause = t;
	}

	/**
	 * Construct BlogerException, wrapping existing throwable.
	 * 
	 * @param t
	 *            existing exception to be wrapped.
	 */
	public BlogerException(Throwable t) {
		rootCause = t;
	}

	/**
	 * Get root cause object, or null if none.
	 * 
	 * @return Root cause or null if none.
	 */
	public Throwable getRootCause() {
		return rootCause;
	}

	/**
	 * Get root cause message.
	 * 
	 * @return Root cause message.
	 */
	public String getRootCauseMessage() {
		String rmessage = null;

		if (null != getRootCause()) {
			if (null != getRootCause().getCause()) {
				rmessage = getRootCause().getCause().getMessage();
			}

			if (null == rmessage) {
				if (null == (rmessage = getRootCause().getMessage())) {
					if (null == (rmessage = super.getMessage())) {
						rmessage = "NO ERROR MESSAGE";
					}
				}
			} else {

			}
		}
		return rmessage;
	}

	/**
	 * Print stack trace for exception and for root cause exception if there is
	 * one.
	 * 
	 */
	public void printStackTrace() {
		super.printStackTrace();
		if (null != rootCause) {
			System.out.println("--- ROOT CAUSE ---");
			rootCause.printStackTrace();
		}
	}

	/**
	 * Print stack trace for exception and for root cause exception if there is
	 * one.
	 * 
	 * @param s
	 */
	public void printStackTrace(PrintStream s) {
		super.printStackTrace(s);
		if (null != rootCause) {
			s.println("--- ROOT CAUSE ---");
			rootCause.printStackTrace(s);
		}
	}

	/**
	 * Print stack trace for exception and for root cause exception if there is
	 * one.
	 * 
	 * @param s
	 */
	public void printStackTrace(PrintWriter s) {
		super.printStackTrace(s);
		if (null != rootCause) {
			s.println("--- ROOT CAUSE ---");
			rootCause.printStackTrace(s);
		}
	}
}
